#include "ControlledObject.h"
#include "Renderer.h"

namespace Nezha
{
	ControlledObject::ControlledObject()
		:mController(NULL)
	{
	}

	ControlledObject::~ControlledObject()
	{
		if(mController)
		{
			mController->detachObject(this);
		}
	}

	void Controller::affect(float delta)
	{
		// implemention do something before this.
		for(PArray<ControlledObject*>::iterator it = mControlledObjects.begin(); it != mControlledObjects.end(); it++)
		{
			(*it)->notifyAffected();
		}
	}

	void Controller::attachObject(ControlledObject* c)
	{
		if(!c)
			return;

		PArray<ControlledObject*>::iterator it = find(mControlledObjects.begin(), mControlledObjects.end(), c);

		if(it != mControlledObjects.end())
		{
			return;
		}

		mControlledObjects.push_back(c);
		c->_setController(this);
	}

	void Controller::detachObject(ControlledObject* co)
	{
		if(co)
		{
			PArray<ControlledObject*>::iterator it = find(mControlledObjects.begin(), mControlledObjects.end(), co);

			if(it != mControlledObjects.end())
			{
				(*it)->_setController(NULL);
				mControlledObjects.erase(it);
			}
		}
	}

	void ContollerJoint::update(float dt)
	{
		for(PArray<Controller*>::iterator it = mControllers.begin(); it != mControllers.end(); it++)
		{
			(*it)->affect(dt);
		}
	}

	void ContollerJoint::addController(Controller* c)
	{
		if(c)
		{
			PArray<Controller*>::iterator it = find(mControllers.begin(), mControllers.end(), c);

			if(it == mControllers.end())
			{
				mControllers.push_back(c);
			}
		}
	}

	void ContollerJoint::removeController(Controller* c)
	{
		if(c)
		{
			PArray<Controller*>::iterator it = find(mControllers.begin(), mControllers.end(), c);

			if(it != mControllers.end())
			{
				mControllers.erase(it);
			}
		}
	}

	Controller* ContollerJoint::getController(u32 i)
	{
		if(i < mControllers.size())
		{
			return mControllers[i];
		}

		return NULL;
	}

	void ContollerJoint::removeAll()
	{
		mControllers.clear();
	}

}//end namespace Nezha